package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserVerifyRequest;
import com.cskaoyan.user.dto.UserVerifyResponse;
import com.cskaoyan.user.service.IVerifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 创建日期: 2022/05/19 20:16
 *
 * @author JinLu Zhou
 */
@Service
@Slf4j
public class IVerifyServiceImpl implements IVerifyService {

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    MemberMapper memberMapper;

    @Override
    @Transactional
    public UserVerifyResponse verify(UserVerifyRequest request) {
        UserVerifyResponse response = new UserVerifyResponse();
        try {
            Example example = new Example(UserVerify.class);
            example.createCriteria()
                    .andEqualTo("uuid", request.getUuid())
                    .andEqualTo("username", request.getUserName());
            List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);
            if (userVerifies.size() == 1) {
                //认证成功
                response.setCode(UserRetCode.SUCCESS.getCode());
                response.setMsg(UserRetCode.SUCCESS.getMessage());
                UserVerify userVerify = userVerifies.get(0);
                userVerify.setIsVerify("Y");
                userVerifyMapper.updateByExampleSelective(userVerify,example);

                Example memberExample = new Example(Member.class);
                memberExample.createCriteria().andEqualTo("username", request.getUserName());
                List<Member> members = memberMapper.selectByExample(memberExample);
                Member member = members.get(0);
                member.setIsVerified("Y");
                memberMapper.updateByExample(member,memberExample);
            }else {
                //认证不成功
                response.setCode(UserRetCode.USERVERIFY_FAILURE.getCode());
                response.setMsg(UserRetCode.USERVERIFY_FAILURE.getMessage());
            }
        } catch (Exception e) {
            log.error("IVerifyServiceImpl.verify occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }
}
